package com.ews.onlineexchange.service.schedule;

import java.util.Calendar;
import java.util.Date;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.ScheduleExpression;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.persistence.EntityManager;

import org.hibernate.CacheMode;
import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;

import com.ews.onlineexchange.model.QualificationCert;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.service.SmsService;

@Singleton
@Startup
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class SupplierWarnTimer {

	@Resource
	TimerService timerService;
	
	@Inject
	EntityManager entityManager;
	
	@Inject
	SmsService smsService;
	
//	@PostConstruct
	public void init() {
		ScheduleExpression schedule = new ScheduleExpression();	
		schedule.hour(9);
		timerService.createCalendarTimer(schedule, new TimerConfig("supplierWarnTimer", false));
		
//		check();
	}
	
	private static final String QUERY_ALL_VALID_SUPPLIER_EQL = ""
			+ "	SELECT			ss"
			+ "	FROM			ServiceSupplier ss "
			+ "	WHERE			ss.valid = true "
			+ "	AND				ss.busnissAllotedTime IS NOT NULL";
//	@Timeout
	@Schedule(hour="9", minute="0", second="0", info = "supplierWarnTimer", persistent = false)
	public void check() {
		
		
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) + 5);
		Date startingWarnDate = cal.getTime();
		Date now = new Date();
		
		Session session = entityManager.unwrap( Session.class );
		ScrollableResults sr = session.createQuery(QUERY_ALL_VALID_SUPPLIER_EQL).setCacheMode( CacheMode.IGNORE )
		        .scroll( ScrollMode.FORWARD_ONLY );
		
		while (sr.next()) {
			ServiceSupplier serviceSupplier = (ServiceSupplier) sr.get(0);
			if (serviceSupplier.getBusnissAllotedTime().before(startingWarnDate)
					&& serviceSupplier.getBusnissAllotedTime().after(now)) {
				smsService.addSupplierExpire(serviceSupplier);
			}
		}
	}
	
	
}
